package com.iacrqq.sedaf.executor;

import com.iacrqq.sedaf.config.Configuration;
import com.iacrqq.sedaf.profile.Profilable;
import com.iacrqq.sedaf.thread.DefaultThreadPool;
import com.iacrqq.sedaf.thread.ThreadPool;

/**
 * 
 * @author sihai
 *
 */
public class DefaultThreadPoolExecutor implements Executor, Profilable {

	private String name;
	private Configuration configuration;
	private Runnable runnable;
	private ThreadPool threadPool;
	
	public DefaultThreadPoolExecutor(String name, Runnable runnable)
	{
		this.name = name;
		this.runnable = runnable;
	}
	
	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void init(Configuration config) throws Exception {
		this.configuration = config;
		String threadPoolName = makeThreadPoolName();
		threadPool = new DefaultThreadPool(threadPoolName, runnable);
		threadPool.init(config);
	}

	@Override
	public void destroy() throws Exception {
		threadPool.destroy();
	}

	@Override
	public void pause() {
		threadPool.pause();
	}

	@Override
	public void start() {
		threadPool.start();
	}

	@Override
	public void stop() {
		threadPool.stop();
	}

	@Override
	public int size() {
		return threadPool.size();
	}
	
	@Override
	public int getCurrentThreadCount()
	{
		return threadPool.size();
	}

	@Override
	public int getIdleTreadCount()
	{
		return threadPool.idleSize();
	}
	
	private String makeThreadPoolName()
	{
		return new StringBuilder(name).append(".threadpool").toString();
	}
	
	@Override
	public int idleThread(int num)
	{
		return threadPool.idle(num);
	}

	@Override
	public int addThread(int num)
	{
		return threadPool.addThreads(num);
	}

	@Override
	public int removeThread(int num)
	{
		return threadPool.removeThreads(num);
	}
}
